﻿namespace DistrRTgen
{
    using System;
    using System.Collections.Generic;
    using System.Reflection;

    internal class IndexHashList
    {
        private DistrRTgenConnector _Connection;
        private uint _MinAvailableIH = 4;
        private List<IndexHash> _WorkUnits;

        public IndexHashList()
        {
            Logger.AddLogLine("Initializing IndexHashList()", LoggerLevel.LOG_DEBUG);
            this._WorkUnits = new List<IndexHash>();
            this._Connection = new DistrRTgenConnector();
        }

        public void Add(IndexHash IH)
        {
            this._WorkUnits.Add(IH);
        }

        public IndexHash GetFirstAvailable()
        {
            uint NumAvailable = 0;
            for (int i = 0; i < this._WorkUnits.Count; i++)
            {
                if (!this[i].InUse)
                {
                    if (this[i].ExpireTime.ToLocalTime() < DateTime.Now)
                    {
                        this.Remove(this[i]);
                        i--;
                    }
                    else
                    {
                        NumAvailable++;
                    }
                }
            }
            if (NumAvailable < this._MinAvailableIH)
            {
                IndexHash[] IndexHashList = this._Connection.RequestHashToIndex(this._MinAvailableIH - NumAvailable);
                if (IndexHashList != null)
                {
                    for (int i = 0; i < IndexHashList.Length; i++)
                    {
                        this.Add(IndexHashList[i]);
                    }
                }
            }
            for (int i = 0; i < this._WorkUnits.Count; i++)
            {
                if (!this[i].InUse)
                {
                    return this[i];
                }
            }
            return null;
        }

        public void Remove(IndexHash IH)
        {
            this._WorkUnits.Remove(IH);
        }

        public IndexHash this[int i]
        {
            get
            {
                return this._WorkUnits[i];
            }
        }

        public List<IndexHash> WorkUnits
        {
            get
            {
                return this._WorkUnits;
            }
        }
    }
}

